import { topicApi } from '/api/topic'
import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { checkAuth, getDomoUser } from '/store/actions'

Component({
  data: {
    loading: true,
    show: false,
    showDialog: false,
    topicId: 0,
    giftList: [] as DomoRewardGift[],
    selectedIndex: -1,
    count: 0,
    balance: 0,
    // 是否打赏成功了
    rewardSuccess: false,
    // 点击了打赏，失败和成功都显示结果
    showrewardResult: false,
  },

  pageLifetimes: {
    show() {
      this.setData({
        giftList: GlobalData.rewardGiftList,
        currencyName: GlobalData.currencyName,
      })
      $event.on('after:rewardGiftList', this, () => {
        this.setData({ giftList: GlobalData.rewardGiftList })
      })
      $event.on('reward', this, ({ topicId }: { topicId: number }) => {
        this.onShow(topicId)
      })
    },
  },

  methods: {
    emptyHandler() {},
    async onShow(topicId: number) {
      await checkAuth()
      if (GlobalData.logged == null) {
        await getDomoUser()
      }
      const balance = GlobalData.logged!.currency!.sum
      this.setData({ show: true, showDialog: true, loading: true, topicId, balance })
      // const tabbar = this.getTabBar!()
      // tabbar && tabbar.setData({ hide: true })
      $event.emit('feed:hideTabbar')
    },

    onClose() {
      if (!this.data.showDialog) return
      this.onCloseForce()
    },

    onCloseForce() {
      this.setData({ show: false, showDialog: false })
      setTimeout(() => {
        this.setData({ topicId: 0, count: 0, selectedIndex: -1 })
      }, 400)
      // if (this.getTabBar) {
      //   const tabbar = this.getTabBar()
      //   tabbar && tabbar.setData({ hide: false })
      // }
      $event.emit('feed:showTabbar')
    },

    onSelectItem(event: any) {
      const { index } = event.currentTarget.dataset
      if (index === this.data.selectedIndex) {
        this.setData({ count: this.data.count + 1 })
      } else {
        this.setData({ count: 1, selectedIndex: index })
      }
    },

    async onSubmit() {
      const balance = GlobalData.logged!.currency!.sum
      const gift = this.data.giftList[this.data.selectedIndex]
      if (gift.price * this.data.count > balance) {
        this.goRecharge()
        this.onCloseForce()
        // 跳转到充值积分
        return
      }

      let rewardSuccess

      try {
        const { currency_sum } = await topicApi.rewardTopic(this.data.topicId, {
          gift_id: gift.id,
          numbers: this.data.count,
        })

        GlobalData.logged!.currency!.sum = +currency_sum
        rewardSuccess = true

        // 广播打赏成功
        $event.emit('after:reward')
      } catch (error) {
        rewardSuccess = false
      }
      this.setData({ showDialog: false, showrewardResult: true, rewardSuccess })
    },

    goRecharge() {
      wx.navigateTo({
        url: '/pages/recharge/recharge',
      })
    },
  },
})
